// pages/music/music.js
var template = require("../../global.js");
const innerAudioContext = wx.createInnerAudioContext();
const app = getApp();
var musicId;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        loadFinished: false, //页面加载完成
        theme: "", //页面主题
        sliderCurrentLength: 0, //当前slider的长度
        sliderLength: 0, //slider的最大值，根据歌曲长度设置
        currentTime: "00:00",//当前音乐播放时间
        musicLength: "00:00", //音乐总长度
        duration: 0,  //音乐长度,数值
        musicStatus: "pause", //音乐是否暂停
        musicImg: "", //音乐图片
        musicName: "", //音乐名
        singer: "",  //歌手名
        musicSrc: "", //音乐链接
        lyrics: [], //歌词数组 
        scrollTop: 0 //当前歌词滚动条的位置
    },

    //   返回
    back: function (e) {
        wx.navigateBack();
    },

    // 滑动过程中暂停播放
    slideChanging: function (e) {
        innerAudioContext.pause(); //触发onPause()事件
    },

    // 滑动结束继续播放
    slideChange: function (e) {
        var currentTime = e.detail.value; //slider的长度就是已播放时间的近似值
        innerAudioContext.seek(currentTime);
        innerAudioContext.play(); //触发onPlay()事件
        this.setData({
            musicStatus: 'play',
            sliderCurrentLength: e.detail.value
        })
    },

    // 播放状态改变
    changeStatus: function (e) {
        var status = e.currentTarget.dataset.status;
        // 之前是播放状态
        if (status == "play") {
            innerAudioContext.pause();
        }
        // 之前是暂停状态
        if (status == "pause") {
            innerAudioContext.play();
        }
    },

    // 暂停
    pause: function () {
        // 避免频繁setData
        if (this.data.musicStatus != "pause") {
            this.setData({
                musicStatus: 'pause'
            })
        }
    },

    // 播放
    play: function () {
        this.data.musicStatus = "play"
        this.playing();  //继续记时
        this.setData({
            musicStatus: 'play'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        musicId = options.musicId;
        // 绑定播放结束,暂停事件,播放事件
        innerAudioContext.onEnded(this.pause);
        innerAudioContext.onPause(this.pause);
        innerAudioContext.onPlay(this.play);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var that = this;
        if (musicId == null) {
            this.setData({
                loadFinished: true
            })
            return
        }
        // 获取歌曲信息
        template.request("http://123.207.63.106:3000/song/detail?ids=" + musicId, "get", function (res) {
            if (res.data.code == 200) {
                var musicName = res.data.songs[0].name;
                if (musicName == null) {
                    musicName = "未知歌曲"
                }
                var singer = res.data.songs[0].ar[0].name;
                var musicImg = res.data.songs[0].al.picUrl;
                that.setData({
                    musicName: musicName,
                    singer: singer,
                    musicImg: musicImg
                })
            }
        })

        // 获取音频文件
        template.request("http://123.207.63.106:3000/music/url?id=" + musicId, "get", function (res) {
            var data = res.data;
            if (data.code == 200) {
                var musicSrc = data.data[0].url;
                innerAudioContext.src = musicSrc;
                // 可以播放
                innerAudioContext.onCanplay(function (res) {
                    that.callPlay();
                })
            }
        })

        //获取歌词信息
        template.request("http://123.207.63.106:3000/lyric?id=" + musicId, "get", function (res) {
            if (res.data.code != 200) {
                that.setData({
                    lyrics: [{
                        time: "-1",
                        word: "网络异常"
                    }]
                })
                return;
            } else if (res.data.nolyric) {
                that.setData({
                    lyrics: [{
                        time: "-1",
                        word: "无歌词"
                    }]
                })
                return;
            } else {
                that.setLyrics(res.data.lrc.lyric);
            }
        })
    },

    //设置歌词
    setLyrics: function (lyric) {
        let array = lyric.split('\n'); //根据回车分割行政数组。
        let reg = /^\[(.+)\](.*)$/; //正则，匹配中括号内的时间和中括号后的歌词内容
        //创建歌词数组，每一项都是一段歌词对象，key为time和word
        let lrcArray = array.map(function (string) {
            let matches = string.match(reg);
            //存在null的可能，所以应该加个判断以免报错。
            if (matches) {
                // 根据.切分时间字符串
                var arr = matches[1].split(/[\.\:]/);
                return {
                    time: parseInt(arr[0]) * 60 + parseInt(arr[1]),  //转化为秒
                    word: matches[2],
                    active: false
                }
            }
            // 没有返回值会保留一个undefined值
            else {
                return {
                    time: "",
                    word: "",
                    active: false
                }
            }
        })

        // 去掉为空的元素
        for (let i = 0; i < lrcArray.length; i++) {
            if (lrcArray[i].word == "") {
                lrcArray.splice(i, 1);
            }
        }
        this.setData({
            lyrics: lrcArray
        })
    },

    // 开始播放事件
    callPlay: function () {
        var that = this;
        var loadTime = 2;
        // 一秒读取一次duration
        var timer = setInterval(function () {
            var duration = innerAudioContext.duration;
            if (duration != 0) {
                loadTime--;
            }
            if (loadTime == 0) {
                clearInterval(timer);
                innerAudioContext.play(); //开始播放
                that.playing(); //开始记时
                that.data.duration = duration;
                var minute = parseInt(duration / 60);
                var second = parseInt(duration % 60);
                function setTime(number) {
                    return number >= 10 ? number + '' : '0' + number
                }
                var musicLength = setTime(minute) + ":" + setTime(second);
                that.setData({
                    sliderLength: parseInt(duration), //1s作为slider的步长，音乐长度为总长度
                    musicLength: musicLength,
                    musicStatus: "play",
                    loadFinished: true, //关闭加载中图标
                })
            }
        }, 1000)
    },

    // 正在播放事件
    playing: function () {
        // 通过播放的状态来结束setTimeout
        if(this.data.musicStatus == "pause"){
            return
        }
        var nowSeconds = innerAudioContext.currentTime;
        // 当前单词的判断
        var lyrics = this.data.lyrics;
        for (let i = 0; i < lyrics.length; i++) {
            // 最后一句歌词或者其他歌词
            if ((i == lyrics.length - 1) || (nowSeconds >= parseInt(lyrics[i].time) && nowSeconds <= parseInt(lyrics[i + 1].time))) {
                // 将全部的active先改为false
                for (let j = 0; j < lyrics.length; j++) {
                    lyrics[j].active = false;
                }
                lyrics[i].active = true;
                this.setData({
                    lyrics: lyrics,
                    scrollTop: (i - 1) * 40  //
                })
                break;
            }
        }
        // 把当前时间转换为正常时间表达式
        var minute = parseInt(nowSeconds / 60);
        var second = parseInt(nowSeconds % 60);
        function setTime(number) {
            return number >= 10 ? number + '' : '0' + number
        }
        var currentTime = setTime(minute) + ":" + setTime(second);
        var sliderCurrentLength = parseInt(nowSeconds); //slider长度与播放时间绑定
        this.setData({
            currentTime: currentTime,
            sliderCurrentLength: sliderCurrentLength,
        })
        setTimeout(this.playing, 500);
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var theme = app.globalData.theme;
        this.setData({
            theme: theme
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})